package com.changgou.interceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;

/**
 * 微服务之间的认证
 *      通过Feign进行调用时,拼接token请求头,能够顺利进行令牌认证.
 */
@Component
public class FeignInterceptor implements RequestInterceptor {


    @Override
    public void apply(RequestTemplate requestTemplate) {
        //将请求头中的token获取出来,通过Feign,添加到路由的请求中.
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if(requestAttributes != null) {
            //通过RequestAttributes(接口)强制类型转换成实现类(子类).
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if(request != null){
                //获取请求头所有的key
                Enumeration<String> headerNames = request.getHeaderNames();
                if(headerNames != null){
                    //获取jwt令牌的请求头,Authorization
                    while (headerNames.hasMoreElements()){
                        String headerName = headerNames.nextElement();
                        System.out.println("headerName : "+headerName);
                        System.out.println("headerValue : "+request.getHeader(headerName));
                        if("authorization".equals(headerName)){
                            //获取请求头的value
                            String headerValue = request.getHeader(headerName);
                            //拼接请求头
                            requestTemplate.header(headerName,headerValue);
                        }
                    }
                }
            }

        }
    }
}
